package com.endava.spring_ioc.service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.endava.spring_ioc.beans.Account;
import com.endava.spring_ioc.dao.AccountDao;

/**
 * The implementation of interface <code>AccountService</code>. We use
 * constructor injection, where we add at constructor a interface of type
 * <code>AccountDao</code>.
 * 
 * @author acojocar
 * 
 */
public class AccountServiceImpl implements AccountService {

	private AccountDao accountDao;

	/**
	 * Implicit constructor.
	 */
	public AccountServiceImpl() {
		super();
	}

	/**
	 * Constructor injection. Another method is with annotations.
	 * 
	 * @param accountDao
	 *            the interface <code>AccountDao</code>
	 */
	// @Autowired
	public AccountServiceImpl(AccountDao accountDao) {
		super();
		this.accountDao = accountDao;
	}

	@Override
	public int addAccount(Account account) {
		return accountDao.addAccount(account);
	}

	@Override
	public List<Account> getAllAccounts() {
		ResultSet rs = null;
		Account account;

		try {
			rs = accountDao.getAllAccounts();
			while (rs.next()) {
				String type = rs.getString("type_account");
				int accountID = rs.getInt("id_account");
				int amount = rs.getInt("amount");

				account = new Account(accountID, type, amount);
				accountDao.addAccount(account);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return accountDao.getAccounts();
	}

	@Override
	public boolean deleteAccount(Integer accountID) {
		try {
			ResultSet rs = accountDao.getAccountByID(accountID);
			if (!rs.next()) {
				return false;
			} else {
				accountDao.deleteAccount(accountID);
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

	}

	@Override
	public boolean addAccount(Integer accountID, String accountType, Integer amount) {
		try {
			ResultSet rs = accountDao.getAccountByID(accountID);
			if (!rs.next()) {
				accountDao.addAccount(accountID, accountType, amount);
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

}
